/**
 * 
 */
package org.elephas.webapp.frontend.validator;

import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.validator.AbstractValidator;
import org.elephas.service.BlogNotFoundException;
import org.elephas.service.BlogFinder;

/**
 * Checks whether the given blog name already exists.
 * 
 * @author Gerolf Seitz
 * 
 */
public class UniqueBlogNameValidator extends AbstractValidator {
	private static final long serialVersionUID = 1L;

	@SpringBean
	private BlogFinder service;

	/**
	 * Construct.
	 */
	public UniqueBlogNameValidator() {
		InjectorHolder.getInjector().inject(this);
	}

	@Override
	protected void onValidate(IValidatable validatable) {
		String name = (String) validatable.getValue();
		boolean isUnique = false;
		try {
			service.findByName(name);
		} catch (BlogNotFoundException e) {
			// this is what we actually want
			isUnique = true;
		}
		if (!isUnique) {
			error(validatable);
		}
	}
}